package fr.paulmasson.jfreex.ui;

import java.util.ArrayList;
import java.util.TreeSet;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import fr.paulmasson.jfreex.channels.LiveChannel;

public class ChannelsList {
	
	
public static Composite create(Composite father, final TreeSet<LiveChannel> liveChannels) {
		
		final ScrolledComposite scrollComposite = new ScrolledComposite(father, SWT.V_SCROLL);

		final Table table = new Table (scrollComposite, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER);
		table.setLinesVisible (true);
		table.setHeaderVisible (false);
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.heightHint = 200;
		table.setLayoutData(data);
		String[] titles = {" "};
		for (int i=0; i<titles.length; i++) {
			TableColumn column = new TableColumn (table, SWT.NONE);
			column.setText (titles [i]);
		}	

		for (LiveChannel liveChannel : liveChannels) {
			TableItem item = new TableItem (table, SWT.NONE);
			item.setText (0, liveChannel.getTitle());
			try {
			item.setImage(0,new Image(Display.getCurrent(),liveChannel.getIconPath()));
			} catch (Exception e) {}

			
		}
		
		for (int i=0; i<titles.length; i++) {
			table.getColumn (i).pack ();
		}
		
		scrollComposite.setContent(table);
		scrollComposite.setExpandVertical(true);
		scrollComposite.setExpandHorizontal(true);

		table.addSelectionListener(new SelectionListener() {
			
			@Override
			public void widgetSelected(SelectionEvent arg0) {
			}
			
			/**
			 * DefaultSelected equals Double-click
			 */
			@Override
			public void widgetDefaultSelected(SelectionEvent evt) {
				int index = table.getSelectionIndex() + 1;
				for (LiveChannel c : liveChannels) {
					if (c.getId()==index) {
						fireChannelChanged(c);
						break;
					}
				}
			}
		});
		
		return scrollComposite;
	}

	private static ArrayList<ChannelsListListener> listeners = new ArrayList<ChannelsListListener>();
	
	public void addChannelsListListener(ChannelsListListener listener) {
		listeners.add(listener);
	}
	
	private static void fireChannelChanged(LiveChannel channel) {
		for (ChannelsListListener listener : listeners) {
			listener.ChannelChanged(channel);
		}
	}
	

}
